<?php

class ReportsController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','checkStatus','beeyeclonereport','loadReports','plainupdate','mailmyreports','mailmyuserreports','ReportsUnregisterCronJob','ReportsRegisterCronJob'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Reports;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Reports']))
		{
			$model->attributes=$_POST['Reports'];

			if($model->save())
				$this->redirect(array('admin'));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */

        public $ber_docName = "c:/Temp/Test.qvw";

	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Reports']))
		{
                        WeekdaysHasTblReports::model()->deleteAll('tbl_reports_report_id = :tbl_reports_report_id',array(':tbl_reports_report_id'=>$id));
			if(isset($_POST['Reports']['tblWeekdays'])){
                            if(is_array($_POST['Reports']['tblWeekdays'])){
                                foreach($_POST['Reports']['tblWeekdays'] AS $value){
                                    $WDRecord = new WeekdaysHasTblReports();
                                    $WDRecord->tbl_reports_report_id = $id;
                                    $WDRecord->tbl_weekdays_weekday_id = $value;
                                    $WDRecord->save();
                                }
                            }
                        }
                        $model->attributes=$_POST['Reports'];
			if($model->save())
				$this->redirect(array('admin','id'=>$model->report_id));
		}

                $subModel = new Recipient();
                $subModel->report_id = $model->report_id;

                $criteria=new CDbCriteria(array(
                    'condition'=>'report_id = '.$id,
                    'with'=> array('org'),
                ));

                $dataProvider=new CActiveDataProvider('Recipient',array(
                    'criteria'=>$criteria,
                ));

		$this->render('update',array(
			'model'=>$model,
                        'submodel'=>$subModel,
                        'dataprovider'=>$dataProvider,
		));
	}


	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
                        //delete associated weekdays
                        WeekdaysHasTblReports::model()->deleteAll('tbl_reports_report_id = :tbl_reports_report_id',array(':tbl_reports_report_id'=>$id));
                        //find all recuipients
                        $Reps = Recipient::model()->findAll('report_id = :report_id',array(':report_id'=>$id));
                        foreach($Reps As $Rep){
                            Qvfilters::model()->deleteAll('rec_id = :rec_id',array(':rec_id'=>$Rep->rec_id));
                            Recipient::model()->findByPK($Rep->rec_id)->delete();
                        }
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{            
                $user_id = Yii::app()->getModule('user')->user()->profile->org_id;
                $criteria=new CDbCriteria(array(
                    'condition'=>'t.org_id = :org_id OR organisationHasTblOrganisations.tbl_organisation_org_childid = :org_id',
                    'params'=>array(':org_id'=>$user_id),
                    'order'=>'report.name',
                    'with'=> array('report','org','org.organisationHasTblOrganisations'),
                ));

		$dataProvider=new CActiveDataProvider('Recipient',array(
                        'criteria'=>$criteria,
                        'pagination'=>array(
                            'pageSize'=>100
                        ),
                    ));

		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Reports('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Reports']))
			$model->attributes=$_GET['Reports'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{

              $criteria = new CDbCriteria;
              $criteria->condition = 'tbl_reports_report_id=:report_id';
              $criteria->select = 'tbl_weekdays_weekday_id';
              $criteria->params=array(':report_id'=>$id);

              $tblWeekdaysQuery = WeekdaysHasTblReports::model()->findAll($criteria);
              $options = array();
              foreach($tblWeekdaysQuery AS $record){
                  array_push($options, $record->tbl_weekdays_weekday_id);
              }

                $model=Reports::model()->findByPk((int)$id);
                if($model===null)
                        throw new CHttpException(404,'The requested page does not exist.');

                $model->tblWeekdays = $options;
                $this->ber_docName = $model->ber_docName;
                return $model;
        }
        

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='reports-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

        public function actionLoadReports(){
            if(isset($_POST['Reports']['ber_docName'])){
                ini_set('soap.wsdl_cache_enabled',0);

                $client=new beeyeQvDocumentService(Yii::app()->params->SOAPServerBeeye,array('soap_version'=>SOAP_1_1,'trace'=>1,'exceptions'=>1));
                $client->soap_defentcoding='UTF-8';

                $myFields = new GetbeeyeQvReportList();
                $myFields->_docName=$_POST['Reports']['ber_docName'];

                $fieldList = $client->GetbeeyeQvReportList($myFields);
                
                /*
                 * @information
                 * Here I mark all reports as deleted, so old reports will disapear in the list
                 */
                $data = Reportids::model()->findAll('rep_docName = :docName',array(':docName'=>strtoupper($myFields->_docName)));
                foreach($data As $report){
                    $ReportIdRecord = Reportids::model()->findByPK($report->rep_id);
                    $ReportIdRecord->rep_deleted = 1;
                    $ReportIdRecord->save();
                }
                unset($data);
                

                //var_dump($fieldList);
                //echo count($fieldList->GetbeeyeQvReportListResult->beeyeQvReports);

                if(count($fieldList->GetbeeyeQvReportListResult->beeyeQvReports)>1){
                    foreach($fieldList->GetbeeyeQvReportListResult->beeyeQvReports as $beeyeQvReports){
                        $DocName = strtoupper($beeyeQvReports->DocName);
                        $FieldName = $beeyeQvReports->ReportName;
                        $ReportLabel = $beeyeQvReports->ReportLabel;
                        if(!is_Object(Reportids::model()->find('rep_docName = :docName AND rep_reportId = :rep_reportId',array(':docName'=>$DocName,':rep_reportId'=>$FieldName)))){
                            $saveField = new Reportids();
                            $saveField->rep_docName = $DocName;
                            $saveField->rep_reportId = $FieldName;
                            $saveField->rep_label = $ReportLabel;
                            $saveField->rep_deleted = 0;
                            $saveField->save();
                        }else{
                            $ActualModel = Reportids::model()->find('rep_docName = :docName AND rep_reportId = :rep_reportId',array(':docName'=>$DocName,':rep_reportId'=>$FieldName));
                            $ActualModel->rep_deleted = 0;
                            $ActualModel->rep_label = $ReportLabel;
                            $ActualModel->save();
                        }
                    }
                }else{
                    $mbReports = $fieldList->GetbeeyeQvReportListResult->beeyeQvReports;
                    $saveField = new Reportids();
                    $saveField->rep_docName = strtoupper($mbReports->DocName);
                    $saveField->rep_reportId = $mbReports->ReportName;
                    $saveField->rep_label = $mbReports->ReportLabel;
                    $saveField->rep_deleted = 0;
                    $saveField->save();
                }
                
                $data = Reportids::model()->findAll('rep_docName = :docName AND rep_deleted=0',array(':docName'=>strtoupper($myFields->_docName)));
                
                $data=CHtml::listData($data,'rep_id','rep_label');
                foreach($data as $value=>$name)
                {
                    echo CHtml::tag('option',array('value'=>$value),CHtml::encode($name),true);
                }
            }
        }

        //start of the mailer content, to be cleaned up
   public function actionMailMyReports($id){
        ini_set('soap.wsdl_cache_enabled',0);

        try{
            $QVMailerWS = new beeyeQvDocumentService(Yii::app()->params->SOAPServerBeeye,array('soap_version'=>SOAP_1_1,'trace'=>1,'exceptions'=>1));
            $QVMailerWS->soap_defentcoding = 'UTF-8';

            $MailReports = $this->buildBeeyeParameter($id);
            
            $result = $QVMailerWS->SendbeeyeQvReport($MailReports);
            var_dump($QVMailerWS->__getLastRequest());
            //var_dump($QVMailerWS->__getLastResponse());
        }
        catch(Exception $e){
            echo 'Exception abgefangen: '. $e->getMessage(). "\n";
        }
        Yii::app()->end();
    }

    public function actionMailMyUserReports($id,$rec_id,$org_id=NULL){

        ini_set('soap.wsdl_cache_enabled',0);

        try{
            $QVMailerWS = new QVMailerWS(Yii::app()->params->SOAPServerMailer,array('soap_version'=>SOAP_1_1,'trace'=>1,'exceptions'=>1));
            $QVMailerWS->soap_defentcoding = 'UTF-8';

            $MailReports = new QVmailReports();
            $MailReports->id = $id;
            $MailReports->report = $this->buildParameter($id,$rec_id,$org_id);
            $MailReports->password = 'abcde';

            $result = $QVMailerWS->mailReports($MailReports);
            //var_dump($QVMailerWS->__getLastRequest());
            //var_dump($QVMailerWS->__getLastResponse());
        }
        catch(Exception $e){
            echo 'Exception abgefangen: '. $e->getMessage(). "\n";
        }
    }

    /*
     * @function actionCheckStatus($id)
     * @property integer $id
     * @description Returns the log information to the browser
     */
    
    public function actioncheckStatus($id){
        
        ini_set('soap.wsdl_cache_enabled',0);
        
        $result = array();
        try{
            $QVMailerWS = new QVMailerWS(Yii::app()->params->SOAPServerMailer,array('soap_version'=>SOAP_1_1,'trace'=>1,'exceptions'=>1));
            $QVMailerWS->soap_defentcoding = 'UTF-8';

            $StatusCheck = new QVcheckStatus();
            $StatusCheck->id = $id;
            $StatusCheck->numberOfRecords = 100;

            $checkStatusResult = $QVMailerWS->checkStatus($StatusCheck);
            
            foreach($checkStatusResult->checkStatusResult->StatusListe As $value){
                foreach($value as $item){
                    $result[]=$item;
                }
            }
        }catch(Exception $e){
            echo 'Exception abgefangen: '. $e->getMessage(). "\n";
        }
        return $result;
    }

    public function actionReportsRegisterCronJob($id){

        $this->actionReportsUnregisterCronJob($id);

        ini_set('soap.wsdl_cache_enabled',0);
        
        //Hier hole ich mir die Werte vom Bericht, damit ich Sie gleich verwenden kann
        $MyCronBericht = Reports::model()->findByPK($id);

        $MailReports = new QVmailReports();
        $MailReports->report = $this->buildParameter($id);

        $CronJob = new CronJob();
        // Template $CronJob->DateString = '####-##-01 10:00' monatlich;
        // Template $CronJob->DateString = '####-##-## 10:00' in Kombi mit Wochentag  - woechentlich;
        // Template $CronJob->DateString = '####-##-## ##:00' stuendlich;

        //build up of datesting
        $myDateString = "####-##-";
        if($MyCronBericht->s_zyklus == 3){
            $myDateString.= sprintf("%02d",$MyCronBericht->s_zyklus_start);
        }else{
            $myDateString.= "##";
        }
        $myDateString.=" ".$MyCronBericht->s_zyklus_time;

        $CronJob->DateString = $myDateString;

        $CronJob->WeekdayFilter = "*";
        if($MyCronBericht->s_zyklus<3){
              //zusammenbauen des Tagesstring
              $ar_ber_zyklus_gap=array(1=>'Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday');            
            
              $criteria = new CDbCriteria;
              $criteria->condition = 'tbl_reports_report_id=:report_id';
              $criteria->select = 'tbl_weekdays_weekday_id';
              $criteria->params=array(':report_id'=>$id);

              $tblWeekdaysQuery = WeekdaysHasTblReports::model()->findAll($criteria);
              $dayvalues = array();
              foreach($tblWeekdaysQuery AS $record){
                  array_push($dayvalues, $ar_ber_zyklus_gap[$record->tbl_weekdays_weekday_id]);
              }
            
              $CronJob->WeekdayFilter = implode(",",$dayvalues);
        }

        $CronJob->Id = $id;

        try{
            $QVMailerWS = new QVMailerWS(Yii::app()->params->SOAPServerMailer,array('soap_version'=>SOAP_1_1,'trace'=>1,'exceptions'=>1));
            $QVMailerWS->soap_defentcoding = 'UTF-8';

            $MyCronJob = new registerCronJob();
            $MyCronJob->cronjob = $CronJob;
            $MyCronJob->report = $MailReports->report;
            $MyCronJob->password = 'abcde';

            $result = $QVMailerWS->registerCronJob($MyCronJob);

//            var_dump($QVMailerWS->__getLastRequest());

        }catch(Exception $e){
            echo 'Exception abgefangen: '. $e->getMessage(). "\n";
        }
    }

    public function actionReportsUnregisterCronJob($id){
        ini_set('soap.wsdl_cache_enabled',0);

        try{
            $QVMailerWS = new QVMailerWS(Yii::app()->params->SOAPServerMailer,array('soap_version'=>SOAP_1_1,'trace'=>1,'exceptions'=>1));
            $QVMailerWS->soap_defentcoding = 'UTF-8';

            $MyCronJob = new unregisterCronJob();
            $MyCronJob->id = $id;
            $MyCronJob->password = 'abcde';

            $result = $QVMailerWS->unregisterCronJob($MyCronJob);
        }catch(Exception $e){
            echo 'Exception abgefangen: '. $e->getMessage(). "\n";
        }
    }

    public function buildBeeyeParameter($id,$rec_id="0",$org_id=NULL){
        $target_encoding = "UTF-8";
        $SingleReport = Reports::model()->findByPK($id);

        $doc = new SendbeeyeQvReport();
        $doc->_docName = $SingleReport->ber_docName;

        $BerID=str_replace("Document\\","",Reportids::model()->findByPK($SingleReport->rep_id)->rep_reportId);
        $doc->_reportName=$BerID;

        if($rec_id == 0){
            $criteria = new CDbCriteria(
                array(
                        'condition'=>'report_id = '.$id,
                        'with'=> array('org'),
                ));
        }else{
            $criteria = new CDbCriteria(
                array(
                        'condition'=>'report_id = '.$id.' AND rec_id = '.$rec_id,
                        'with'=> array('org'),
                ));
        }

        $RCPS=Recipient::model()->findAll($criteria);
        //schleife für alle empfänger
        foreach($RCPS As $RCP) {
            if($RCP->org->is_group){
                //lets get all recipients for this setting...
                $GroupContact = OrganisationHasTblOrganisation::model()->with('tblOrganisationOrgChild')->findAll('tbl_organisation_org_id = :tbl_organisation_org_id',array(':tbl_organisation_org_id'=>$RCP->org_id));
                foreach($GroupContact As $Contact){
                    $Mailer = new beeyeQvRecipient();
                    $Mailer->RecipientAdress = mb_convert_encoding(Kommunikation::model()->findbyPK($Contact->kom_id)->kom_information,$target_encoding);

                    //the filter
                    $Filters=array();
                    $MyFilters = Qvfilters::model()->with('qvf')->findAll('rec_id = :rec_id',array(':rec_id'=>$RCP->rec_id));
                    if(count($MyFilters)>=1){
                        foreach($MyFilters AS $MyFilter){
                             $Filters[] = $this->beeyeConditionCleaner($MyFilter->filter,Qvfields::model()->findByPK($MyFilter->qvf_id)->qvf_fieldName);
                        }
                        $Mailer->Filters = $Filters;
                    }else{
                        $Mailer->Filters = "";
                    }

                    $Mailer->ntName=$Contact->tblOrganisationOrgChild->ntname;
                    $Mailer->mailBody = htmlspecialchars_decode($SingleReport->mail_body);
                    $Mailer->mailSubject=$SingleReport->mail_subject;
                    $Recipients[]=$Mailer;
                }
            }else{
                $Mailer = new beeyeQvRecipient();
                $Mailer->RecipientAdress = mb_convert_encoding(Kommunikation::model()->findbyPK($RCP->kom_id)->kom_information,$target_encoding);

                //the filter
                $Filters=array();
                $MyFilters = Qvfilters::model()->with('qvf')->findAll('rec_id = :rec_id',array(':rec_id'=>$RCP->rec_id));
                if(count($MyFilters)>=1){
                    foreach($MyFilters AS $MyFilter){
                        $Filters[] = $this->beeyeConditionCleaner($MyFilter->filter,Qvfields::model()->findByPK($MyFilter->qvf_id)->qvf_fieldName);
                    }

                    $Mailer->Filters = $Filters;
                }else{
                    $Mailer->Filters = "";
                }

                $Mailer->ntName=$Contact->tblOrganisationOrgChild->ntname;
                $Mailer->mailBody = htmlspecialchars_decode($SingleReport->mail_body);
                $Mailer->mailSubject=$SingleReport->mail_subject;
                $Recipients[]=$Mailer;
            }
            unset($Mailer,$MyFilter,$Filters);
        }
        $doc->_Recipients=$Recipients;

        return $doc;
    }

    public function buildParameter($id,$rec_id="0",$org_id=NULL){
            $target_encoding = "UTF-8";

            $SingleReport = Reports::model()->findByPK($id);

            $doc = new QVReports();

            $doc->MailBody=htmlspecialchars_decode($SingleReport->mail_body);
            $doc->MailSubject=$SingleReport->mail_subject;
            $doc->QlikViewFile=$SingleReport->ber_docName;

            if($rec_id == 0){
                $criteria = new CDbCriteria(
                    array(
                            'condition'=>'report_id = '.$id,
                            'with'=> array('org'),
                    ));
            }else{
                $criteria = new CDbCriteria(
                    array(
                            'condition'=>'report_id = '.$id.' AND rec_id = '.$rec_id,
                            'with'=> array('org'),
                    ));
            }

            $RCPS=Recipient::model()->findAll($criteria);
            //schleife für alle empfänger
            foreach($RCPS As $RCP) {
                if($RCP->org->is_group){
                    //lets get all recipients for this setting...
                    if($org_id == NULL){
                        $GroupContact = OrganisationHasTblOrganisation::model()->with('tblOrganisationOrgChild')->findAll('tbl_organisation_org_id = :tbl_organisation_org_id',array(':tbl_organisation_org_id'=>$RCP->org_id));
                    }else{
                        $GroupContact = OrganisationHasTblOrganisation::model()->with('tblOrganisationOrgChild')->findAll('tbl_organisation_org_childid = :tbl_organisation_org_id',array(':tbl_organisation_org_id'=>$org_id));
                    }
                    foreach($GroupContact As $Contact){
                        $Mailer = new QVRecipient();
                        $Mailer->BookmarkName='';
                        $Mailer->Email=mb_convert_encoding(Kommunikation::model()->findbyPK($Contact->kom_id)->kom_information,$target_encoding);

                        //the filter
                        $Filters=array();
                        $MyFilters = Qvfilters::model()->with('qvf')->findAll('rec_id = :rec_id',array(':rec_id'=>$RCP->rec_id));
                        if(count($MyFilters)>=1){
                            foreach($MyFilters AS $MyFilter){
                                $Filter = new QVFieldSelection();
                                $Filter->FieldName = Qvfields::model()->findByPK($MyFilter->qvf_id)->qvf_fieldName;
                                $Filter->FieldValue = $this->ConditionCleaner($MyFilter->filter);
                                $Filters[] = $Filter;
                                unset($Filter);
                            }

                            $Mailer->FieldSelection = $Filters;
                        }else{
                            $Mailer->FieldSelection = "";
                        }

                        $Mailer->NTNAME=$Contact->tblOrganisationOrgChild->ntname;
                        $Recipients[]=$Mailer;
                    }
                }else{
                    $Mailer = new QVRecipient();
                    $Mailer->BookmarkName='';
                    $Mailer->Email=mb_convert_encoding(Kommunikation::model()->findbyPK($RCP->kom_id)->kom_information,$target_encoding);

                    //the filter
                    $Filters=array();
                    $MyFilters = Qvfilters::model()->with('qvf')->findAll('rec_id = :rec_id',array(':rec_id'=>$RCP->rec_id));
                    if(count($MyFilters)>=1){
                        foreach($MyFilters AS $MyFilter){
                            $Filter = new QVFieldSelection();
                            $Filter->FieldName = Qvfields::model()->findByPK($MyFilter->qvf_id)->qvf_fieldName;
                            $Filter->FieldValue = $this->ConditionCleaner($MyFilter->filter);
                            $Filters[] = $Filter;
                            unset($Filter);
                        }

                        $Mailer->FieldSelection = $Filters;
                    }else{
                        $Mailer->FieldSelection = "";
                    }

                    $Mailer->NTNAME=$RCP->org->ntname;
                    $Recipients[]=$Mailer;
                }
                unset($Mailer,$MyFilter,$Filters);
            }
            $doc->Recipients=$Recipients;

            $BerID=str_replace("Document\\","",Reportids::model()->findByPK($SingleReport->rep_id)->rep_reportId);
            $doc->ReportId=$BerID;

            $doc->ReportName=$SingleReport->name;

            return $doc;
    }

    private function ConditionCleaner($Condidtion){
        $mShort= array(1=>'Jan',2=>'Feb',3=>'Mar',4=>'Apr',5=>'Mai',6=>'Jun',7=>'Jul',8=>'Aug',9=>'Sep',10=>'Okt',11=>'Nov',12=>'Dez');
        $newvalues = array();
        if(preg_match("/\,/",$Condidtion)){
            $values = preg_split("/\,/",$Condidtion);
            foreach($values AS $value){
                if($value != ''){
                    $newvalues[]=trim($value);
                }
            }
        }else{
            $newvalues[]=$Condidtion;
        }
        return $newvalues;
    }

    private function beeyeConditionCleaner($Condidtion,$FieldName){
        //inititilisieren der filter
        $mShort= array(1=>'Jan',2=>'Feb',3=>'Mar',4=>'Apr',5=>'Mai',6=>'Jun',7=>'Jul',8=>'Aug',9=>'Sep',10=>'Okt',11=>'Nov',12=>'Dez');
        $newvalues = array();
        if(preg_match("/\,/",$Condidtion)){
            $values = preg_split("/\,/",$Condidtion);
            foreach($values AS $value){
                if($value != ''){
                    $beeyeQvValue = new beeyeQvValue();
                    $beeyeQvValue->FieldName = $FieldName;
                    $beeyeQvValue->FieldValue = trim($value);                   
                    $newvalues[]=$beeyeQvValue;
                }
            }
        }else{
            $beeyeQvValue = new beeyeQvValue();
            $beeyeQvValue->FieldName = $FieldName;
            $beeyeQvValue->FieldValue = trim($Condidtion);                   
            $newvalues[]=$beeyeQvValue;
        }
        $Filter = new beeyeQvFieldSelection();
        $Filter->FieldName = $FieldName;
        $Filter->FieldValues=$newvalues;
        return $Filter;
    }
    
        /**
         * Clone a report with all his recipients and filters
         * @param Id the id of the cloning feature
         */
        
        public function actionBeeyeCloneReport($id){
            //load the old report
            $ExistingReport = Reports::model()->findByPK($id);
            
            //create new report
            $CloneReport = new Reports();
            
            $CloneReport->ber_docName = $ExistingReport->ber_docName;
            $CloneReport->cdate = $ExistingReport->cdate;
            $CloneReport->description = $ExistingReport->description;
            $CloneReport->mail_body = $ExistingReport->mail_body;
            $CloneReport->mail_subject = $ExistingReport->mail_subject;
            $CloneReport->name = "Clone: " . $ExistingReport->name;
            $CloneReport->org_id = $ExistingReport->org_id;
            $CloneReport->production_time = $ExistingReport->production_time;
            $CloneReport->rep_id = $ExistingReport->rep_id;
            // PK needs is set by database $CloneReport->report_id = $ExistingReport->report_id;
            $CloneReport->s_zyklus = $ExistingReport->s_zyklus;
            $CloneReport->s_zyklus_gap = $ExistingReport->s_zyklus_gap;
            $CloneReport->s_zyklus_time = $ExistingReport->s_zyklus_time;
            $CloneReport->s_zyklus_start = $ExistingReport->s_zyklus_start;
            $CloneReport->type = $ExistingReport->type;
            
            $CloneReport->save();
            
            $ExistingRecipients = Recipient::model()->findAll('report_id = :report_id',array(':report_id'=>$ExistingReport->report_id));
            
            foreach($ExistingRecipients As $ExistingRecipient){
                // User Kopieren
                $CloneRecipient = new Recipient();
                $CloneRecipient->org_id = $ExistingRecipient->org_id;
                $CloneRecipient->kom_id = $ExistingRecipient->kom_id;
                $CloneRecipient->report_id = $CloneReport->report_id;
                $CloneRecipient->save();
                
                $ExistingFilters = Qvfilters::model()->findAll('rec_id = :rec_id',array('rec_id'=>$ExistingRecipient->rec_id));
                foreach($ExistingFilters As $ExistingFilter){
                    //Filter Kopieren
                    $CloneFilter = new Qvfilters();
                    $CloneFilter->rec_id = $CloneRecipient->rec_id;
                    $CloneFilter->qvf_id = $ExistingFilter->qvf_id;
                    $CloneFilter->filter = $ExistingFilter->filter;
                    $CloneFilter->save();
                    
                    unset($CloneFilter);
                }
                
                unset($CloneRecipient);
            }
            return true;    
        }

}
